<script setup lang="ts">
import conditionsRedemption from "./conditionsRedemption.vue";
import { ref, reactive, onMounted, h } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { regionData } from "@/utils/chinaArea";
import type { PaginationProps } from "@pureadmin/table";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { conditionsRedemptionItemProps } from "../utils/types";
import { deviceDetection } from "@pureadmin/utils";
import ABProgress from "@/components/ABProgress/index.vue";

import Eye from "~icons/ri/Eye-line";
import Refresh from "~icons/ep/refresh";
import refund from "~icons/ri/currency-line";
import exchange from "~icons/ri/exchange-box-line";
import dayjs from "dayjs";
import numeral from "numeral";
import CustomerDetail from "./customerDetail.vue";
import {
  exchange_query,
  exchange_quota,
  company_info,
  exchange_getByCondition,
  exchange_costlogs,
  exchange_taskDetail,
  exchange_chargelogs
} from "@/api/redemption";
const emit = defineEmits(["onSearch", "refreshProgress"]);

// 兑领弹窗
const drawer = ref(false);

// 打开弹窗
function openDrawer() {
  drawer.value = true;
}

const formRef = ref();
const form = reactive({
  keyword: "",
  address: "", // 所在地区
  industry: "", // 所属行业
  range: "", // 经营范围
  enterpriseMax: "", // 企业最大评估值
  enterpriseMin: "", // 企业最小评估值
  benefitMax: "", // 效益评估最大值
  benefitMin: "" // 效益最小评估值
});
const dataList = ref([]);
const loading = ref(true);
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true
});
const columns: TableColumnList = [
  {
    label: "企业名称",
    prop: "name",
    minWidth: 200
  },
  {
    label: "法人",
    prop: "faren",
    minWidth: 100
  },
  {
    label: "注册日期",
    prop: "date",
    minWidth: 140
  },
  // {
  //   label: "电话",
  //   prop: "phone",
  //   minWidth: 140
  // },
  {
    label: "统一社会信用代码",
    prop: "code",
    minWidth: 200
  },
  {
    label: "企业类型",
    // prop: "type",
    minWidth: 100,
    slot: "type"
  },
  {
    label: "地区",
    prop: "address_path",
    minWidth: 180
  },
  {
    label: "行业",
    prop: "classify",
    minWidth: 140
  },
  {
    label: "经营范围",
    prop: "scope",
    minWidth: 140
  },
  {
    label: "操作",
    fixed: "right",
    slot: "operation"
  }
];

// 按条件兑领
const conditionsRedemptionFormRef = ref();
function conditionsRedemptionClick() {
  addDialog({
    title: "按条件兑领",
    props: {
      formInline: {
        address: "",
        // industryOptions: industryList.value,
        industry: null,
        enterpriseMin: null,
        enterpriseMax: null,
        benefitMin: null,
        benefitMax: null,
        range: "",
        num: null,
        // sortMode: 1,
        labelId: "",
        page: "",
        labelName: ""
      }
    },
    width: "680px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () =>
      h(conditionsRedemption, {
        ref: conditionsRedemptionFormRef,
        formInline: null
      }),
    beforeSure: (done, { options }) => {
      const FormRef = conditionsRedemptionFormRef.value.getRef();
      const curData = options.props.formInline as conditionsRedemptionItemProps;
      function chores() {
        message(`操作成功！`, {
          type: "success"
        });
        done(); // 关闭弹框
        drawer.value = false;
        emit("onSearch"); // 刷新表格数据
      }
      // console.log("curData", curData);
      FormRef.validate(valid => {
        if (valid) {
          // 客户参数选项，至少需要填写一个
          ElMessageBox.confirm("确定执行该操作？", "重要提示", {
            type: "warning"
          })
            .then(() => {
              let address;
              address = curData.address
                .split("/")
                .filter(item => item !== "市辖区");
              curData.address = address.join("/");
              // console.log( curData )
              exchange_getByCondition(curData).then(res => {
                if (res.code == 1000) {
                  localStorage.setItem('progressID', res.data?.logId)
                  emit('refreshProgress', res.data?.logId)
                  chores();
                }
              });
            })
            .catch(() => {});
        }
      });
    }
  });
}

let timer: any;
const Process = ref(0); // 进度
// 每隔3秒查询一次任务
function onStartQuery(task_id: any) {
  showProgress.value = true;
  timer = setInterval(() => {
    exchange_taskDetail({
      task_id
    })
      .then(res => {
        if (res.code == 1000) {
          if (res.data.status == "done") {
            Process.value = Number(res.data.process || 0) || 0;
            showProgress.value = false;
            clearInterval(timer);
          }
        }
      })
      .catch(err => {
        showProgress.value = false;
        clearInterval(timer);
      });
  }, 3000);
}

function handleSizeChange(val: number) {
  pagination.pageSize = val;
  onSearch();
}

function handleCurrentChange(val: number) {
  pagination.currentPage = val;
  onSearch();
}
async function onSearch() {
  loading.value = true;
  exchange_query({
    size: pagination.pageSize,
    page: pagination.currentPage,
    address: form.address,
    industry: form.industry,
    range: form.range,
    enterpriseMax: form.enterpriseMax,
    enterpriseMin: form.enterpriseMin,
    benefitMax: form.benefitMax,
    benefitMin: form.benefitMin
  }).then(res => {
    if (res.code == 1000) {
      loading.value = false;
      dataList.value = res.data.list;
      pagination.total = res.data.total;
    }
  });
  // setTimeout(() => {

  // }, 500);
}

const resetForm = formEl => {
  if (!formEl) return;
  // formEl.resetFields();
  form.keyword = "";
  form.address = "";
  form.industry = "";
  form.range = "";
  form.enterpriseMax = "";
  form.enterpriseMin = "";
  form.benefitMax = "";
  form.benefitMin = "";
  onSearch();
};
// 公司额度
const num = ref();
exchange_quota().then(res => {
  if (res.code == 1000) {
    num.value = res.data;
  }
});
// 加盟商信息
const info = ref();
company_info().then(res => {
  if (res.code == 1000) {
    info.value = res.data;
  }
});
/** 兑领记录 */
const list = ref([]);
const pagination2 = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true
});
function getRedemption() {
  exchange_costlogs({
    page: pagination2.currentPage,
    size: pagination2.pageSize
  }).then(res => {
    if (res.code == 1000) {
      pagination2.total = res.data.total;
      list.value = res.data.list.map(i => ({
        ...i,
        created_at: i.created_at
          ? dayjs(i.created_at * 1000).format("YYYY-MM-DD HH:mm:ss")
          : ""
      }));
    }
  });
}
const drawer2 = ref(false); // 兑领记录和充值记录
const columns2: TableColumnList = [
  {
    label: "标签",
    prop: "tag",
    minWidth: 200
  },
  {
    label: "目标数",
    prop: "aim_num",
    minWidth: 100
  },
  {
    label: "兑领条数",
    prop: "cost",
    minWidth: 100
  },
  {
    label: "状态",
    // prop: "status",
    minWidth: 100,
    slot: "status"
  },
  {
    label: "时间",
    prop: "created_at",
    minWidth: 140
  }
];
const columns3: TableColumnList = [
  {
    label: "时间",
    prop: "created_at",
    minWidth: 140
  },
  {
    label: "充值余额（元）",
    prop: "amount",
    minWidth: 200
  },
  {
    label: "备注",
    prop: "remark",
    minWidth: 200
  },
];
onMounted(() => {
  onSearch();
});

defineExpose({ openDrawer });
const detailRef = ref();
function lookCustomer(row) {
  detailRef.value.openDrawer(row);
}
const handleChange = e => {
  form.address = e.join("/");
};
// 打开兑领/充值弹窗
const typeNumber = ref(0); // 判断打开什么弹框
function changeOpen(i) {
  drawer2.value = true;
  typeNumber.value = i;
  list.value = []
  if (i == 1) {
    getRecharge();
  } else {
    getRedemption();
  }
}
function handleSizeChange2(val: number) {
  pagination2.pageSize = val;
  getRedemption();
}

function handleCurrentChange2(val: number) {
  pagination2.currentPage = val;
  getRedemption();
}
// 充值记录
function getRecharge() {
  exchange_chargelogs({
    page: pagination2.currentPage,
    size: pagination2.pageSize
  }).then(res => {
    if(res.code == 1000){
      pagination2.total = res.data.total;
      list.value = res.data.list.map(i => ({
        ...i,
        created_at: i.created_at
          ? dayjs(i.created_at * 1000).format("YYYY-MM-DD HH:mm:ss")
          : ""
      }));
    }
  });
}
const showProgress = ref(false);
</script>

<template>
  <div>
    <ABProgress
      v-model:show="showProgress"
      v-model:process="Process"
    ></ABProgress>
    <el-drawer v-model="drawer" size="78%" :with-header="false" direction="ltr">
      <el-container>
        <el-aside width="200px">
          <div class="enterprise">
            <img src="@/assets/header.png" />
            <p>公司：{{ info.company_name }}</p>
          </div>
          <el-divider style="margin: 0" />
          <div class="number">
            <span>可用兑领条数:</span>
            <p>{{ numeral(num).format("0,000") }} 条</p>
            <el-button type="primary">充值</el-button>
          </div>
          <div class="cell">
            <el-divider style="margin: 0" />
            <div class="cell-item" @click="changeOpen(1)">
              <IconifyIconOffline
                :icon="refund"
                style="width: 22px; height: 22px"
              />
              <p>充值记录</p>
            </div>
            <el-divider style="margin: 0" />
            <div class="cell-item" @click="changeOpen(2)">
              <IconifyIconOffline
                :icon="exchange"
                style="width: 22px; height: 22px"
              />
              <p>兑领记录</p>
            </div>
            <el-divider style="margin: 0" />
          </div>
        </el-aside>
        <el-container>
          <el-header>兑领</el-header>
          <el-main>
            <el-form
              ref="formRef"
              :inline="true"
              :model="form"
              class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
            >
              <el-form-item prop="name">
                <el-input
                  v-model="form.keyword"
                  placeholder="客户名称/企业名称"
                  clearable
                  class="w-[180px]!"
                />
              </el-form-item>
              <el-form-item prop="range">
                <el-input
                  v-model="form.range"
                  placeholder="经营范围"
                  clearable
                  class="w-[180px]!"
                />
              </el-form-item>
              <el-form-item label="企业评估">
                <div class="flex">
                  <el-form-item prop="enterpriseMin">
                    <el-input
                      v-model="form.enterpriseMin"
                      placeholder="最小值"
                      clearable
                      class="w-[98px]!"
                    />
                  </el-form-item>
                  <div class="text-center pl-1 pr-1" :span="4">至</div>
                  <el-form-item prop="enterpriseMax">
                    <el-input
                      v-model="form.enterpriseMax"
                      placeholder="最大值"
                      clearable
                      class="w-[98px]!"
                    />
                  </el-form-item>
                </div>
              </el-form-item>
              <el-form-item label="效益评估">
                <div class="flex">
                  <el-form-item prop="benefitMin">
                    <el-input
                      v-model="form.benefitMin"
                      placeholder="最小值"
                      clearable
                      class="w-[98px]!"
                    />
                  </el-form-item>
                  <div class="text-center pl-1 pr-1" :span="4">至</div>
                  <el-form-item prop="benefitMax">
                    <el-input
                      v-model="form.benefitMax"
                      placeholder="最大值"
                      clearable
                      class="w-[98px]!"
                    />
                  </el-form-item>
                </div>
              </el-form-item>
              <el-form-item prop="industry">
                <!-- <el-select
                  v-model="form.industry"
                  placeholder="所属行业"
                  clearable
                  class="w-[120px]!"
                >
                  <el-option v-for="(item, index) in industryList" :key="index" :label="item.label" :value="item.value" />
                </el-select> -->
                <el-input
                  v-model="form.industry"
                  placeholder="所属行业"
                  clearable
                  class="w-[108px]!"
                />
              </el-form-item>
              <el-form-item prop="regionData">
                <el-cascader
                  placeholder="所在地区"
                  :props="{ value: 'label' }"
                  :options="regionData"
                  clearable
                  class="w-[120px]!"
                  @change="handleChange"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  :icon="useRenderIcon('ri/search-line')"
                  :loading="loading"
                  @click="onSearch"
                >
                  查询
                </el-button>
                <el-button
                  :icon="useRenderIcon(Refresh)"
                  @click="resetForm(formRef)"
                >
                  重置
                </el-button>
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  :icon="useRenderIcon('ri:filter-line')"
                  @click="conditionsRedemptionClick()"
                >
                  按条件兑领
                </el-button>
              </el-form-item>
            </el-form>

            <PureTableBar title="" :columns="columns" @refresh="onSearch">
              <template v-slot="{ size, dynamicColumns }">
                <pure-table
                  align-whole="center"
                  showOverflowTooltip
                  table-layout="auto"
                  :loading="loading"
                  :size="size"
                  adaptive
                  :adaptiveConfig="{ offsetBottom: 108 }"
                  :data="dataList"
                  :columns="dynamicColumns"
                  :pagination="{ ...pagination, size }"
                  :header-cell-style="{
                    background: 'var(--el-fill-color-light)',
                    color: 'var(--el-text-color-primary)'
                  }"
                  @page-size-change="handleSizeChange"
                  @page-current-change="handleCurrentChange"
                >
                  <template #type="{ row }">
                    <div>有限公司</div>
                  </template>
                  <template #operation="{ row }">
                    <el-button
                      class="reset-margin"
                      link
                      type="primary"
                      :size="size"
                      :icon="useRenderIcon(Eye)"
                      @click="lookCustomer(row)"
                    >
                    </el-button>
                  </template>
                </pure-table>
              </template>
            </PureTableBar>
          </el-main>
        </el-container>
      </el-container>
    </el-drawer>
    <el-drawer
      v-model="drawer2"
      :title="typeNumber == 1 ? '充值记录' : '兑领记录'"
      size="50%"
    >
      <PureTableBar v-if="typeNumber == 2" title="" :columns="columns2" @refresh="onSearch">
        <template v-slot="{ size, dynamicColumns }">
          <pure-table
            align-whole="center"
            showOverflowTooltip
            table-layout="auto"
            :loading="loading"
            :size="size"
            adaptive
            :adaptiveConfig="{ offsetBottom: 108 }"
            :data="list"
            :columns="dynamicColumns"
            :pagination="{ ...pagination2, size }"
            :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }"
            @page-size-change="handleSizeChange2"
            @page-current-change="handleCurrentChange2"
          >
            <template #status="{ row }">
              <div>
                {{
                  row.status == "unstart"
                    ? "未开始"
                    : row.status == "going"
                      ? "进行中"
                      : row.status == "done"
                        ? "已完成"
                        : row.status == "pause"
                          ? "暂停"
                          : "出错"
                }}
              </div>
            </template>
          </pure-table>
        </template>
      </PureTableBar>
      <PureTableBar v-else  :columns="columns3" @refresh="onSearch">
        <template v-slot="{ size, dynamicColumns }">
          <pure-table
            align-whole="center"
            showOverflowTooltip
            table-layout="auto"
            :loading="loading"
            :size="size"
            adaptive
            :adaptiveConfig="{ offsetBottom: 108 }"
            :data="list"
            :columns="dynamicColumns"
            :pagination="{ ...pagination2, size }"
            :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }"
            @page-size-change="handleSizeChange2"
            @page-current-change="handleCurrentChange2"
          >
            <template #status="{ row }">
              <div>
                {{
                  row.status == "unstart"
                    ? "未开始"
                    : row.status == "going"
                      ? "进行中"
                      : row.status == "done"
                        ? "已完成"
                        : row.status == "pause"
                          ? "暂停"
                          : "出错"
                }}
              </div>
            </template>
          </pure-table>
        </template>
      </PureTableBar>
    </el-drawer>
  </div>
  <!-- 客户信息 -->
  <CustomerDetail ref="detailRef" @onSearch="onSearch"></CustomerDetail>
</template>

<style scoped lang="scss">
:deep(.el-drawer__body) {
  padding: 0 !important;
}

:deep(.flex .el-form-item) {
  margin-right: 0 !important;
}

:deep(.el-container) {
  height: 100%;
  background: #f5f5f5;
}

:deep(.el-aside) {
  background: #ffffff;
  padding: 0 8px;
}

.enterprise {
  padding-top: 30px;

  img {
    width: 110px;
    height: 110px;
    border-radius: 50%;
    margin: 0 auto;
    display: block;
  }

  p {
    margin: 20px 0;
    text-align: center;
  }
}

.number {
  padding-top: 20px;
  padding-bottom: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  span {
    display: block;
    text-align: center;
    color: #666666;
  }
  p {
    text-align: center;
    font-weight: bold;
    margin-top: 3px;
    margin-bottom: 15px;
    color: var(--pure-theme-menu-active-before);
  }
}

.cell-item {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;

  p {
    margin-left: 10px;
  }
}

:deep(.el-header) {
  background: #ffffff;
  display: flex;
  align-items: center;
}

:deep(.el-main) {
  padding: 12px;
}
</style>
